package com.dinadi.yidi.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.DailyProductAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.CommentBean;
import com.dinadi.yidi.bean.CommentListRequest;
import com.dinadi.yidi.bean.CommentRequest;
import com.dinadi.yidi.bean.CreativeHotspotDetailsBean;
import com.dinadi.yidi.bean.WriteCommentsBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.IntegralChangeInterface;
import com.dinadi.yidi.ui.view.CommonDialogUtils;
import com.dinadi.yidi.ui.view.ShareMenuPopupWindow;
import com.dinadi.yidi.ui.view.ShowImageWebView;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: JiaYu.He
 * Date: 2017/4/7   每日设计师详情
 * Time: 17:01
 */

public class DailyDesignerActivity extends BaseActivity {
    private View view;
    private TextView tvTitle, tv_more, user_name;
    private Button btn_title_right;
    private ImageView img_no_comment, goto_comment;
    private CircleImageView head_img;
    private ProgressBar pbLoad;
    private ShowImageWebView activity_web;
    private ListView customListView;
    /*添加listview头部尾部*/
    private View headView, footView;
    /*用户详情*/
    private RelativeLayout designer_details;
    private ShareMenuPopupWindow selectImage;
    /*评论*/
    private DailyProductAdapter adapter;
    private List<CommentRequest> mList = new ArrayList<>();
    private int itemIndex;
    private Handler handler = new Handler();
    private int page = 1;
    /*是否第一次进入页面*/
    private boolean isfirst = true;
    private String subjectProductId, title, htmlPath, coverImg;
    private String token, userId;
    /*判断是否登陆*/
    private boolean loginState;
    private int sharePosition;
    private String type, dUserId;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(this).inflate(R.layout.activity_detail_designer, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        btn_title_right = (Button) view.findViewById(R.id.btn_title_right);
        btn_title_right.setBackgroundResource(R.drawable.product_details_icon_share);
        customListView = (ListView) view.findViewById(R.id.custom_listview);
        customListView.setDivider(null);
        headView = getLayoutInflater().inflate(R.layout.creative_hotspot_details_head, customListView, false);
        footView = getLayoutInflater().inflate(R.layout.load_more_footview_layout, customListView, false);
        customListView.addHeaderView(headView);
        customListView.addFooterView(footView);
        activity_web = (ShowImageWebView) headView.findViewById(R.id.activity_web);
        tv_more = (TextView) footView.findViewById(R.id.tvLoadText);
        img_no_comment = (ImageView) footView.findViewById(R.id.img_no_comment);
        pbLoad = (ProgressBar) footView.findViewById(R.id.pbLoad);
        goto_comment = (ImageView) view.findViewById(R.id.goto_comment);
        head_img = (CircleImageView) view.findViewById(R.id.head_img);
        user_name = (TextView) view.findViewById(R.id.user_name);
        designer_details = (RelativeLayout) view.findViewById(R.id.designer_details);

//        activity_web.getSettings().setUseWideViewPort(true);
//        activity_web.getSettings().setLoadWithOverviewMode(true);
//        activity_web.getSettings().setDefaultFontSize((int) 15);
        //支持javascript
        //    activity_web.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放 
//        activity_web.getSettings().setSupportZoom(true);
//        // 设置出现缩放工具 
//        activity_web.getSettings().setBuiltInZoomControls(true);
//        //扩大比例的缩放
//        activity_web.getSettings().setUseWideViewPort(true);
//        //自适应屏幕
//        activity_web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        activity_web.getSettings().setLoadWithOverviewMode(true);

        // 支持缩放(适配到当前屏幕)  
//        WebSettings webSettings = activity_web.getSettings();
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//少于4.4（不包括4.4）用这个  
//            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        }
//        //适应屏幕，大于等于4.4用这个  
//        webSettings.setUseWideViewPort(true);
//        webSettings.setSupportZoom(true);
//        webSettings.setLoadWithOverviewMode(true);


        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        activity_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            // 网页加载结束
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                activity_web.getSettings().setJavaScriptEnabled(true);

                // web 页面加载完成，添加监听图片的点击 js 函数
                activity_web.setImageClickListner();
                //解析 HTML
                activity_web.parseHTML(view);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(DailyDesignerActivity.this, "请检查您的网络设置", Toast.LENGTH_SHORT).show();
            }
        });


        adapter = new DailyProductAdapter(DailyDesignerActivity.this, mList);
        customListView.setAdapter(adapter);

    }

    @Override
    protected void initListener() {
        /**关键在这里，listview滑动监听方法*/
        customListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {


                int lastIndex = adapter.getCount() - 1;
                int item = lastIndex + 2;
                Log.d("TAG", "滑动的Item" + item);
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && itemIndex == item) {
                    isfirst = false;
                    loadData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                itemIndex = firstVisibleItem + visibleItemCount - 1;
                Log.d("TAG", "滑动" + itemIndex);
            }
        });
        registerClickListener(goto_comment, btn_title_right, designer_details);
    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userId = SharePreferencesHelper.getInstance(this).getString("userId");
            token = SharePreferencesHelper.getInstance(this).getString("token");
            loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
            SharePreferencesHelper.getInstance(this).putString("isRefresh", "no");
        }
    }

    @Override
    protected void initData() {
        mList.clear();
        activity_web.clearImgs();
        adapter.notifyDataSetChanged();
        loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
        userId = SharePreferencesHelper.getInstance(this).getString("userId");
        Intent intent = getIntent();
        subjectProductId = intent.getStringExtra("subjectProductId");
        token = SharePreferencesHelper.getInstance(this).getString("token");
        getHotspotDetails();
    }

    private void getHotspotDetails() {
        CreativeHotspotDetailsBean bean = new CreativeHotspotDetailsBean();
        bean.setToken(token);
        bean.setSubjectId(subjectProductId);
        CommonInterface creativeHotspotDetailsInterface = new CommonInterface(this, httpListener);
        creativeHotspotDetailsInterface.getInterface("14005", JSON.toJSONString(bean));
    }


    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.goto_comment:
                /*评论*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    showEditPopup();
                }
                break;
            case R.id.btn_title_right:
                /*分享*/
                ShowPickDialog();
                break;
            case R.id.designer_details:
                /*点击进入用户详情*/
                Intent intent = new Intent(this, DesignerHmePageActivity.class);
                intent.putExtra("type", type);
                intent.putExtra("dUserId", dUserId);
                startActivity(intent);
                break;
            default:
                break;

        }

    }

    /*获取评论列表*/
    private void getComment() {
        CommentBean commentBean = new CommentBean();
        commentBean.setArticleId(subjectProductId);
        commentBean.setPageNum(page + "");
        commentBean.setPageSize("10");
        CommonInterface commentInterface = new CommonInterface(this, httpListener2);
        commentInterface.getInterface("15001", JSON.toJSONString(commentBean));
    }

    private void loadData() {
        tv_more.setText("正在加载...");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_more.setText("上拉加载");
                page = page + 1;
                getComment();
            }
        }, 2000);

    }

    //弹出分享框
    private void ShowPickDialog() {
        if (selectImage == null) {
            selectImage = new ShareMenuPopupWindow(this);
            selectImage.setOnShareClickListener(shareClickListener);
        }
        selectImage.showAtLocation(this.findViewById(R.id.linearlayout_base), Gravity.BOTTOM, 0, 0);
    }

    private ShareMenuPopupWindow.OnShareClickListener shareClickListener = new ShareMenuPopupWindow.OnShareClickListener() {

        @Override
        public void onShareClick(int position) {
            screenshot(position);
        }
    };

    private void share() {
        ShareAction shareAction = new ShareAction(this);
        UMImage thumb = new UMImage(this, coverImg);
        UMWeb web = new UMWeb(htmlPath);
        web.setTitle(title);//标题
        web.setThumb(thumb);  //缩略图
        web.setDescription("分享内容");//描述
        if (sharePosition == 1) {
            shareAction.setCallback(umShareListener).withMedia(web).share();
        } else {
            shareAction.setCallback(umShareListener).withMedia(web).share();

        }
        switch (sharePosition) {

            case 0:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN); // 微信好友
                break;
            case 1:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE);// 微信朋友圈
                break;

        }
        shareAction.share();
    }

    public void screenshot(int position) {
//        if (!LoadDialog.isShowProgressDialog()) {
//            LoadDialog.showProgressDialog(getActivity(), "制作分享数据...", false, false);
        sharePosition = position;
        share();

        //   }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
            selectImage.dismiss();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (loginState == true) {
                IntegralChangeInterface.IntegralChange(DailyDesignerActivity.this, userId, token, "4", "1", "分享成功啦");
            }else {
                ToastUtil.showToast("分享成功啦");
            }
            selectImage.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(DailyDesignerActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
            selectImage.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(DailyDesignerActivity.this, " 分享取消了", Toast.LENGTH_SHORT).show();
            selectImage.dismiss();
        }

    };

    /*评论的弹kuang*/
    private void showEditPopup() {
        //当然是先初始化popupWindow
        final UtilPopupWindow popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_comment, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_creative_hotspot_details, null);
        popupWindow.setPopupWindow(this, windowHeight / 4, layout, layout2, Gravity.BOTTOM);
        TextView canel = (TextView) layout.findViewById(R.id.canel);
        TextView release = (TextView) layout.findViewById(R.id.release);
        final EditText edit_comment = (EditText) layout.findViewById(R.id.edit_comment);
        canel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
           /*自动弹出键盘*/
        edit_comment.setFocusableInTouchMode(true);
        edit_comment.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) edit_comment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(edit_comment, 0);
                           }

                       },
                100);
        release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = null;
                try {
                    content = URLEncoder.encode(edit_comment.getText().toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (content.length() < 1) {
                    toast("内容不能为空哦");
                } else {
                    WriteCommentsBean bean = new WriteCommentsBean();
                    bean.setTargetId(subjectProductId);
                    bean.setFromUserId(userId);
                    bean.setToUserId(userId);
                    bean.setContent(content);
                    bean.setType("1");
                    bean.setToken(token);
                    CommonInterface writeCommentsInterface = new CommonInterface(DailyDesignerActivity.this, httpListener3);
                    writeCommentsInterface.getInterface("15002", JSON.toJSONString(bean));
                    popupWindow.dismiss();

                }

            }
        });
    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                String user = JsonUtil.getFieldValue(response, "user");
                title = JsonUtil.getFieldValue(user, "userName");
                tvTitle.setText(title);
                coverImg = JsonUtil.getFieldValue(user, "headImg");
                htmlPath = JsonUtil.getFieldValue(user, "htmlPath");
                activity_web.loadUrl(htmlPath);
                String userName = JsonUtil.getFieldValue(user, "userName");
                String headImg = JsonUtil.getFieldValue(user, "headImg");
                type = JsonUtil.getFieldValue(user, "type");
                dUserId = JsonUtil.getFieldValue(user, "userId");
                user_name.setText(userName);
                if (headImg != null) {
                    if (!headImg.equals("")) {
                        ImageUtils.loadImageView(DailyDesignerActivity.this, headImg, head_img);
                    } else {
                        ImageUtils.loadImageView(DailyDesignerActivity.this, R.drawable.me_img_default, head_img);
                    }
                }
                getComment();
            } else {
                toast("加载失败");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("加载失败");
        }
    };
    HttpListener httpListener2 = new HttpListener() {

        //评论
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                CommentListRequest commentList = JsonUtil.parseJsonToBean(response, CommentListRequest.class);
                if (commentList.getCommentList().size() == 0) {
                    if (isfirst == true) {
                        tv_more.setVisibility(View.GONE);
                        pbLoad.setVisibility(View.GONE);
                        img_no_comment.setVisibility(View.VISIBLE);
                    } else {
                        tv_more.setVisibility(View.VISIBLE);
                        tv_more.setText("已显示全部评论");
                        tv_more.setTextColor(getResources().getColor(R.color.color_999999));
                        pbLoad.setVisibility(View.GONE);
                    }
                    page = 1;
                    customListView.setOnScrollListener(null);
                } else {
                    img_no_comment.setVisibility(View.GONE);
                }


                mList.addAll(commentList.getCommentList());
                adapter.notifyDataSetChanged();
            } else {
                toast("获取信息失败");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            toast("获取信息失败");
        }
    };
    /*写评论*/
    HttpListener httpListener3 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                IntegralChangeInterface.IntegralChange(DailyDesignerActivity.this, userId, token, "1", "1", "评论成功");

                mList.clear();
                isfirst = false;
                getComment();
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("发表失败");
        }

    };


}
